<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2022 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免费声明 ( https://thinkadmin.top/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\api\model\DaoVipDetail;
use Exception;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\ProductionEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use think\admin\Controller;

/**
 * Class Paypal
 * @package app\api\controller
 */
class Paypal extends Controller
{
    const accept_url = 'https://pay.dadwz.com/api/paypal/payResult';
    protected $client;


    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        parent::initialize();
        // 解决跨域
        $this->corsOptionsHandler();

        // 初始化 PayPal 客户端
        $clientId = config('pay.paypal.client_id'); // 从配置文件读取 clientId
        $clientSecret = config('pay.paypal.secret'); // 从配置文件读取 clientSecret
        $environment = new ProductionEnvironment($clientId, $clientSecret);
        $this->client = new PayPalHttpClient($environment);
    }

    public function corsOptionsHandler()
    {
        if (request()->isOptions()) {
            header('Access-Control-Allow-Origin:*');
            header('Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type,Cookie,token');
            header('Access-Control-Allow-Credentials:true');
            header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
            header('Access-Control-Max-Age:1728000');
            header('Content-Type:text/plain charset=UTF-8');
            header('Content-Length: 0', true);
            header('status: 204');
            header('HTTP/1.0 204 No Content');
        } else {
            header('Access-Control-Allow-Origin:*');
            header('Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type,Cookie,token');
            header('Access-Control-Allow-Credentials:true');
            header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
        }
    }

    /**
     * 获取支付配置
     * http://dadao.36i.cn/api/paypal/getPayPayConfig
     */
    public function getPayPayConfig()
    {
        $data = $this->_vali([
            'name.require' => '缺少用户名~',
            'vip_type.require' => '缺少必要参数~'
        ]);
        $config = config('pay');
        $this_vip = [];
        foreach ($config['vip_list'] as $vip) {
            if ($vip['type'] == $data['vip_type']) $this_vip = $vip;
        }
        if (empty($this_vip)) $this->error('会员类型错误，请正确选择~');
        $trade_sn = create_sn();
        $return_data = $this->createOrder($trade_sn, $this_vip['money'], "{$this_vip['name']}购买");
        $order_info = [
            'user_name' => $data['name'],
            'vip_sn' => $trade_sn,
            'buy_money' => $this_vip['money'],
            'buy_time' => date('Y-m-d H:i:s'),
            'type' => $data['vip_type'],
            'desc' => "PayPal支付 {$this_vip['name']}购买",
            'ip' => $this->app->request->ip(),
            'pay_mode' => 5,
            'transaction_id' => $return_data['id']
        ];
        $bool = DaoVipDetail::mk()->insert($order_info);
        if (!$bool) $this->error('订单生成失败~');
        $this->success('获取成功', [
            "clientId" => config('pay.paypal.client_id'), // 开发者中心 clientId
            "orderId" => $return_data['id'], // 订单 id
            "userAction" => "continue", // 按钮样式 paynow/continue
            "currency" => config('pay.paypal.currency'),
            "environment" => config('pay.paypal.mode') // 运行环境 sandbox(沙盒) / live(线上)
        ]);
    }

    /**
     *  http://dadao.36i.cn/api/paypal/index
     * 创建支付请求
     */
    public function index()
    {
        $trade_sn = create_sn();
        $return_data = $this->createOrder($trade_sn, '0.01', '测试商品描述');
        //dump($return_data);exit;
        $this->success('获取成功', [
            "clientId" => config('pay.paypal.client_id'), // 开发者中心 clientId
            "orderId" => $return_data['id'], // 订单 id
            "userAction" => "continue", // 按钮样式 paynow/continue
            "currency" => config('pay.paypal.currency'),
            "environment" => config('pay.paypal.mode') // 运行环境 sandbox(沙盒) / live(线上)
        ]);
    }

    /**
     * 使用新 SDK 创建支付订单
     * @param $trade_sn
     * @param $price
     * @param $description
     * @return mixed|void
     */
    private function createOrder($trade_sn, $price, $description)
    {
        $request = new OrdersCreateRequest();
        $request->prefer('return=representation');
        $request->body = [
            "intent" => "CAPTURE",
            "purchase_units" => [[
                "reference_id" => $trade_sn,//订单号
                "amount" => [
                    "value" => $price,//订单金额
                    "currency_code" => config('pay.paypal.currency')
                ],
                "description" => $description
            ]],
            "application_context" => [
                "return_url" => self::accept_url . '?success=true',
                "cancel_url" => self::accept_url . '/?success=false'
            ]
        ];

        try {
            $response = $this->client->execute($request);
            sysoplog('createOrder', json_encode($response->result));
            return json_decode(json_encode($response->result), true);
        } catch (Exception $e) {
            echo $e->getMessage();
            die();
        }
    }

    /**
     * 同步回调
     * @return bool|void
     */
    public function payResult()
    {
        sysoplog('payResult', 'GET:' . json_encode($_GET));
        $orderId = trim($_GET['orderId']); // 新 SDK 中使用 token 参数

        if (empty($orderId)) {
            $this->success('支付失败，缺少必要参数~', ['code' => -1]);
        }
        $request = new OrdersCaptureRequest($orderId);
        try {
            $response = $this->client->execute($request);
            sysoplog('payResult', json_encode(json_decode(json_encode($response->result), true)));
            $result = json_decode(json_encode($response->result), true);
        } catch (\Exception $e) {
            sysoplog('payResult', 'Exception:' . $e->getMessage());
            $this->success('catch-支付失败', ['code' => -1]);
        }
        if ($result['status'] == 'COMPLETED') {
            $order_info = DaoVipDetail::mk()->where(['transaction_id' => $orderId])->find();
            if (empty($order_info)) {
                sysoplog('支付异步通知异常', '订单信息未找到，订单号：' . $orderId);
                $this->success("支付失败,订单信息未找到，订单号： $orderId", ['code' => -1]);
            }
            get_order_info($order_info['vip_sn'], $orderId);
            $this->success('支付成功~', ['code' => 1]);
        } else {
            $this->success('支付失败~', ['code' => -1]);
        }
    }
}